/**
 * Copyright (C) 2009 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fee.master.ui.chart;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;

import com.fee.master.model.MonthStat;

/**
 * Average temperature demo chart.
 */
public class LineChart extends AbstractChart {
  
	private static NumberFormat nbf = NumberFormat.getInstance();//新建一个格式化器对象 
	
	static{
		nbf.setMaximumFractionDigits(1);
	}
	/**
   * Returns the chart name.
   * @return the chart name
   */
  public String getName() {
    return "Average temperature";
  }
  
  /**
   * Returns the chart description.
   * @return the chart description
   */
  public String getDesc() {
    return "The average temperature in 4 Greek islands (line chart)";
  }
  
  /**
   * Executes the chart demo.
   * @param context the context
   * @return the built intent
   */
  public GraphicalView execute(Context context,String month) {
    String[] titles = new String[] { "打电话通话时长", "接电话通话时长"};
    List<double[]> x = new ArrayList<double[]>();
    for (int i = 0; i < titles.length; i++) {
      x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
    }
    List<double[]> values = new ArrayList<double[]>();

    double[] callout = getData(context,month,0);
    double[] callin = getData(context,month,1);
    values.add(callout);
    values.add(callin);
   
    int[] colors = new int[] { Color.RED, Color.YELLOW};
    PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND};
    XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
    int length = renderer.getSeriesRendererCount();
    for (int i = 0; i < length; i++) {
      ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
    }
    double callinMax = getYmax(callin);
    double calloutMax = getYmax(callout);
    double yMax = callinMax>calloutMax?callinMax:calloutMax;
    setChartSettings(renderer, "每月打/接电话通话时长（单位：分钟）", "月份", "时间：分钟", 0.5, 12.5, 0, yMax,
        Color.WHITE, Color.WHITE);
    renderer.setXLabels(12);
    renderer.setYLabels(10);
    renderer.setDisplayChartValues(true);
    
    return ChartFactory.getLineChartView(context, buildDataset(titles, x, values), renderer);
  }  
  
  /**
	 * @param context
	 * @param flag 0-call_out 1-call_in
	 * @return
	 */
  private double[] getData(Context context,String month,int flag){
	  Map<Integer,Double> map = new HashMap<Integer,Double>();
	  String year = month.substring(0, 4);
	  String beginMonth = year +"00";
	  String endMonth = year+"13";
	  String selection = null;
	  if(flag ==0){
		  selection = "s_key = 'call_out' and s_month >"+beginMonth+" and s_month <"+endMonth;
	  }else{
		  selection = "s_key = 'call_in' and s_month >"+beginMonth+" and s_month <"+endMonth;
	  }	  
	  Cursor c = context.getContentResolver().query(MonthStat.URI_MONTH_STAT, null, selection, null, null);
	  if(c!= null && c.moveToFirst()){
		  while(!c.isAfterLast()){
			  String key = c.getString(c.getColumnIndex(MonthStat.MONTH)).substring(4,6);
			  Double value = c.getDouble(c.getColumnIndex(MonthStat.NUM));
			  map.put(Integer.valueOf(key), Double.valueOf(nbf.format(value/60)));
			  c.moveToNext();
		  }
	  }
	  c.close();
	  
	  double[] data = new double[12];
	    for(int i=0;i<12;i++){
	    	if(map.containsKey(Integer.valueOf(i+1))){
	    		data[i] = map.get(Integer.valueOf(i+1));
	    	}else{
	    		data[i] = 0;
	    	}
	    }
	   return data;
  }
  
  private double getYmax(double[] data){
	  double temp = 0;
	  for(int i=0;i<data.length;i++){
		  if(data[i]>temp){
			  temp = data[i];
		  }
	  }
	  return temp*2;
  }
  
}
